#include <iostream>

#include <GLUT/glut.h>
#include <OpenGL/gl.h>
#include <math.h>
#include <OpenGL/OpenGL.h>
#include <OpenGL/CGLCurrent.h>

#include "audio.h"
#include "core.h"
#include "image.h"
#include "font.h"
#include "game.h"
#include "keyboard.h"
#include "screen.h"
#include "time.h"

const bool FULL_SCREEN = false;

game::Game *thegame = 0;
font::Font *sys_font = 0;

void myDisplay(void);

void forceSync(void);
void forceSync(void) {
    static bool done = false;
    if (done) return;
    GLint sync = 1;
    CGLSetParameter(CGLGetCurrentContext(), kCGLCPSwapInterval, &sync);
    done = true;
}

void myDisplay(void) {
    forceSync();
    glDisable(GL_BLEND);
    thegame->Draw();
    char framerate[40];
    sprintf(framerate, "%4.2f FPS", gametime::FrameRate());
    font::Draw(sys_font, 20, 20).add_color(COL_WHITE).draw(framerate);
    gametime::Tick();
    keyboard::Tick();
    if (keyboard::IsKeyDown(keyboard::KEY_ESCAPE)) exit(0);
    thegame->Tick(gametime::dt());
    glutSwapBuffers();
	glutPostRedisplay();
}

int main(int argc, char** argv) {
    glutInit(&argc, argv);
    glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH);
    if (!FULL_SCREEN) {
        glutInitWindowSize(SCREEN_WIDTH, SCREEN_HEIGHT);
        glutCreateWindow("game");
    } else {
        char fmt[64];
        sprintf(fmt, "%dx%d:32@60", SCREEN_WIDTH, SCREEN_HEIGHT);
        glutGameModeString(fmt);
        glutEnterGameMode();
    }
    glutDisplayFunc(myDisplay);
    keyboard::Init();
    gametime::Init();
    font::Init();
    sys_font = font::Font::Load("VeraMono.ttf", 12);
    audio::Init(resource_dir().c_str());
    glClearColor(0.0, 0.0, 0.0, 0.0);
    glLineWidth(1.0);
    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    gluOrtho2D(0.0, SCREEN_WIDTH, 0.0, SCREEN_HEIGHT);
    thegame = game::CreateGame();
    thegame->Init();
    glutMainLoop();
    return 0;
}
